package com.shiwaixiangcun.customer.module.heath;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.BloodPressureBean;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.event.EventUtil;
import com.shiwaixiangcun.customer.event.SimpleEvent;
import com.shiwaixiangcun.customer.network.HttpCallBack;
import com.shiwaixiangcun.customer.network.HttpRequest;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.DateUtil;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.LoginOutUtil;
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 血压页面
 *
 * @author Administrator
 */
public class BloodPressureActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.tv_blood_name)
    TextView mTvBloodName;
    @BindView(R.id.tv_shrink_blood)
    TextView mTvShrinkBlood;
    @BindView(R.id.tv_relax_blood)
    TextView mTvRelaxBlood;
    @BindView(R.id.tv_blood_pressure_time)
    TextView mTvBloodPressureTime;
    @BindView(R.id.ll_blood_pressure)
    LinearLayout mLlBloodPressure;
    @BindView(R.id.tv_pressure_qs)
    TextView mTvPressureQs;
    @BindView(R.id.tv_pressure_introduce)
    TextView mTvPressureIntroduce;

    @BindView(R.id.llayout_chart)
    LinearLayout mLlayoutChart;
    @BindView(R.id.rl_history_blood)
    RelativeLayout mRlHistoryBlood;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.back_left)
    ChangeLightImageView mBackLeft;
    @BindView(R.id.tv_page_name)
    TextView mTvPageName;
    @BindView(R.id.tv_top_right)
    TextView mTvTopRight;
    @BindView(R.id.iv_share_right)
    ImageView mIvShareRight;
    @BindView(R.id.iv_sao_right)
    ImageView mIvSaoRight;
    @BindView(R.id.ll_image_right)
    LinearLayout mLlImageRight;
    @BindView(R.id.top_bar_transparent)
    RelativeLayout mTopBarTransparent;
    @BindView(R.id.activity_blood_pressure)
    RelativeLayout mActivityBloodPressure;
    @BindView(R.id.curveChart)
    LineChart mCurveChart;
    private Long customId;

    private List<BloodPressureBean.ElementsBean> mList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_pressure);
        ButterKnife.bind(this);
        EventUtil.getInstance().register(this);
        Bundle bundle = getIntent().getExtras();
        customId = bundle.getLong("customID");
        initView();
        initData();

    }


    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
    }

    private void initView() {
        mBackLeft.setOnClickListener(this);

        mRlHistoryBlood.setOnClickListener(this);

//        // no description text
        mCurveChart.getDescription().setEnabled(false);

        // enable touch gestures
        mCurveChart.setTouchEnabled(true);

        mCurveChart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        mCurveChart.setDragEnabled(true);
        mCurveChart.setScaleEnabled(true);
        mCurveChart.setDrawGridBackground(false);
        mCurveChart.setHighlightPerDragEnabled(false);

        // if disabled, scaling can be done on x- and y-axis separately
        mCurveChart.setPinchZoom(false);

        // set an alternative background color
        mCurveChart.setBackgroundColor(Color.WHITE);


    }

    private void initData() {
        final String refreshToken = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.Refresh_token, "");

        String tokenString = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "");
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("access_token", tokenString);
        hashMap.put("customerId", customId);
        HttpRequest.get(GlobalApi.INSTANCE.getPressureBlood(), hashMap, new HttpCallBack() {
            @Override
            public void onSuccess(String responseJson) {
                Type type = new TypeToken<ResponseEntity<BloodPressureBean>>() {
                }.getType();
                ResponseEntity<BloodPressureBean> responseEntity = JsonUtil.fromJson(responseJson, type);
                if (responseEntity == null) {
                    return;
                }
                switch (responseEntity.getResponseCode()) {
                    case 1001:
                        BloodPressureBean.ElementsBean elementsBean = responseEntity.getData().getElements().get(0);
                        EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.UPDATE_BLOOD_PRESSURE, 1, elementsBean));
                        mList.clear();
                        mList.addAll(responseEntity.getData().getElements());
                        configuration(responseEntity.getData().getElements());
                        break;
                    case 1018:
                        RefreshTokenUtil.refreshToken(mContext, refreshToken);
                        break;
                    case 1019:
                        LoginOutUtil.sendLoginOutUtil(mContext);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFailed(Exception e) {
                Log.e(BUG_TAG, e.toString());
            }
        });

    }

    /**
     * 绘制图表
     *
     * @param elements
     */
    private void configuration(List<BloodPressureBean.ElementsBean> elements) {
        if (elements == null) {
            return;
        }
        if (elements.size() < 2) {
            mLlayoutChart.setVisibility(View.GONE);
        }
        //初始化表格的数据
        int size = elements.size();


        ArrayList<Entry> shrinkList = new ArrayList<>();
        ArrayList<Entry> mRelaxationList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            BloodPressureBean.ElementsBean elementsBean = elements.get(size - i - 1);

            shrinkList.add(new Entry(i + 1, elementsBean.getShrinkBlood()));
            mRelaxationList.add(new Entry(i + 1, elementsBean.getRelaxationBlood()));

        }
        setAxis(mRelaxationList);


        //收缩压数据
        LineDataSet shrinkSet = new LineDataSet(shrinkList, " 收缩压");
        shrinkSet.setAxisDependency(YAxis.AxisDependency.LEFT);

        shrinkSet.setColor(Color.parseColor("#FE9020"));
        shrinkSet.setCircleColor(Color.parseColor("#FE9020"));
        shrinkSet.setLineWidth(2f);
        shrinkSet.setCircleRadius(4f);
        shrinkSet.setFillAlpha(65);


        //舒张压数据
        LineDataSet relaxationSet = new LineDataSet(mRelaxationList, "舒张压");
        relaxationSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        relaxationSet.setColor(Color.parseColor("#1CCC8C"));
        relaxationSet.setCircleColor(Color.parseColor("#1CCC8C"));
        relaxationSet.setLineWidth(2f);
        relaxationSet.setCircleRadius(4f);

        relaxationSet.setFillAlpha(65);


        LineData data = new LineData(shrinkSet, relaxationSet);
        data.setValueTextColor(R.color.black_text_60);
        data.setValueTextSize(10f);
        data.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                int result = (int) value;
                return result + "";
            }
        });

        // set data

        mCurveChart.setData(data);
        mCurveChart.invalidate();


    }

    /**
     * 设置坐标轴
     *
     * @param mRelaxationList
     */
    private void setAxis(ArrayList<Entry> mRelaxationList) {
        //初始化Y轴
        YAxis yAxis = mCurveChart.getAxisLeft();
        yAxis.setDrawGridLines(true);
        yAxis.isDrawBottomYLabelEntryEnabled();
        yAxis.setAxisLineColor(R.color.black_text_40);
        yAxis.setAxisMaximum(160f);
        yAxis.setAxisMinimum(41f);
        yAxis.setYOffset(20f);
        yAxis.setDrawAxisLine(true);
        yAxis.setDrawZeroLine(true);
        yAxis.setZeroLineColor(R.color.black_text_40);
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        mCurveChart.getAxisRight().setEnabled(false);


        //设置X轴
        XAxis xAxis = mCurveChart.getXAxis();
        xAxis.setAxisLineColor(R.color.black_text_40);
        xAxis.setAxisMaximum(mRelaxationList.size() > 8 ? 10 : mRelaxationList.size() + 1);
        xAxis.setAxisMinimum(0f);
        xAxis.setXOffset(1);
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setDrawGridLines(true);
        xAxis.setTextSize(0);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(getResources().getColor(R.color.ui_white));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(SimpleEvent simpleEvent) {
        if (simpleEvent == null || simpleEvent.mEventType != SimpleEvent.UPDATE_BLOOD_PRESSURE) {
            return;
        }
        BloodPressureBean.ElementsBean elementsBean = (BloodPressureBean.ElementsBean) simpleEvent.getData();
        String healthStatus = elementsBean.getHealthStatus();
        String statusEnum = elementsBean.getStatusEnum();
        setBackground(healthStatus, statusEnum);
        mTvShrinkBlood.setText(elementsBean.getShrinkBlood() + "");
        mTvRelaxBlood.setText(elementsBean.getRelaxationBlood() + "");
        mTvPressureIntroduce.setText(elementsBean.getSuggestion());
        mTvBloodPressureTime.setText(DateUtil.INSTANCE.getSecond(elementsBean.getCreateTime()));


    }

    /**
     * 设置头部颜色
     *
     * @param healthStatus 状态
     */
    private void setBackground(String healthStatus, String statusEnum) {
        switch (healthStatus) {
            case "NORMAL":


                mLlBloodPressure.setBackground(getResources().getDrawable(R.drawable.shape_green_gradient));
                break;
            case "WARNING":
                mLlBloodPressure.setBackground(getResources().getDrawable(R.drawable.shape_yellow_gradient));
                break;
            case "DANGER":
                mLlBloodPressure.setBackground(getResources().getDrawable(R.drawable.shape_red_gradient));

                break;
            default:
                break;

        }
        switch (statusEnum) {
            case "Zhengchang":
                mTvBloodName.setText("血压正常");
                mTvPressureQs.setText("您的血压正常");
                mTvPressureQs.setTextColor(Color.parseColor("#15B77C"));
                break;
            case "Piangao":
                mTvBloodName.setText("血压偏高");
                mTvPressureQs.setText("您的血压偏高");
                mTvPressureQs.setTextColor(Color.parseColor("#F96B21"));
                break;
            case "Paindi":
                mTvBloodName.setText("血压偏低");
                mTvPressureQs.setText("您的血压偏低");
                mTvPressureQs.setTextColor(Color.parseColor("#F96B21"));
                break;
            case "Yzpiangao":
                mTvBloodName.setText("血压严重偏高");
                mTvPressureQs.setText("您的血压严重偏高");
                mTvPressureQs.setTextColor(Color.parseColor("#D53635"));
                break;
            default:
                break;
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.rl_blood_pressure:

                break;
            case R.id.back_left:
                finish();
                break;
            case R.id.rl_history_blood:
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("blood_pressure", (ArrayList<? extends Parcelable>) mList);
                readyGo(BloodHistoryActivity.class, bundle);
                break;

            default:
                break;
        }


    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        EventUtil.getInstance().unregister(this);
    }

}